﻿CREATE PROC spObtenEstudiosCaptura
	@pnIdLaboratorio	INT,
	@pnIdSucursal		INT,
	@pnIdResultado		INT,
	@pnIdRecibo			INT
AS
BEGIN
	SET NOCOUNT ON;	
	
	SET @pnIdRecibo = NULLIF(@pnIdRecibo,-1)
	SET @pnIdResultado = NULLIF(@pnIdResultado, -1)
	
	IF @pnIdRecibo IS NOT NULL
	BEGIN
		SELECT	rd.IdEstudio,
				e.NombreEstudio 
		FROM	dbo.ReciboDet		rd (NOLOCK)
		INNER JOIN dbo.CatEstudio	e (NOLOCK)
		ON		rd.IdEstudio		= e.IdEstudio
		AND		rd.IdLaboratorio	= e.IdLaboratorio
		WHERE	rd.IdRecibo			= @pnIdRecibo
		AND		rd.IdLaboratorio	= @pnIdLaboratorio
		AND		rd.IdSucursal		= @pnIdSucursal
		UNION
		SELECT	rd.IdEstudio,
				e.NombreEstudio 
		FROM	dbo.ReciboDet		rd (NOLOCK)
		LEFT JOIN dbo.PaqueteEstudio pe (NOLOCK)
		ON		rd.IdEstudio		= pe.IdPaquete
		AND		rd.EsPaquete		= 1
		AND		rd.IdLaboratorio	= pe.IdLaboratorio
		LEFT JOIN dbo.PaqueteEstudioDet ped (NOLOCK)
		ON		pe.IdPaquete		= ped.IdPaquete
		AND		pe.IdLaboratorio	= ped.IdLaboratorio
		INNER JOIN dbo.CatEstudio	e (NOLOCK)
		ON		ped.IdEstudio		= e.IdEstudio
		AND		ped.IdLaboratorio	= e.IdLaboratorio
		WHERE	rd.IdRecibo			= @pnIdRecibo
		AND		rd.IdLaboratorio	= @pnIdLaboratorio
		AND		rd.IdSucursal		= @pnIdSucursal
	
	END
	ELSE
	BEGIN
		SELECT	rd.IdEstudio,
				e.NombreEstudio 
		FROM	dbo.ResultadoDet		rd (NOLOCK)
		INNER JOIN dbo.CatEstudio	e (NOLOCK)
		ON		rd.IdEstudio		= e.IdEstudio
		AND		rd.IdLaboratorio	= e.IdLaboratorio
		WHERE	rd.IdResultado		= @pnIdResultado
		AND		rd.IdLaboratorio	= @pnIdLaboratorio
		AND		rd.IdSucursal		= @pnIdSucursal
	END
	
	SET NOCOUNT OFF;
END